package com.atguigu.classroom.user.api;

import com.atguigu.classroom.exception.ClassroomException;
import com.atguigu.classroom.model.user.UserInfo;
import com.atguigu.classroom.user.service.UserInfoService;
import com.atguigu.classroom.user.utils.WeChatPropertiesUtils;
import com.atguigu.classroom.utils.JWTHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

@Api(tags = "微信用户授权接口")
@Controller
@RequestMapping("/api/user/wechat/")
public class WechatController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private WxMpService wxMpService;
    @ApiOperation("授权跳转")
    @GetMapping("authorize")
    public String authorize(@RequestParam("returnUrl")String returnUrl){
    /*方法原型:String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state);
    这个方法就是依赖中提供的简便方法来得到用于获取code值的参数所需要访问的地址:
        - https://open.weixin.qq.com/connect/oauth2/authorize?...*/
        String url = wxMpService.oauth2buildAuthorizationUrl(WeChatPropertiesUtils.USERINFOURL,
                WxConsts.OAUTH2_SCOPE_USER_INFO,
                URLEncoder.encode(returnUrl.replace("guiguketan", "#")));
                /*vue中跳转路径例如："localhost:8080/#/live/10",都需要加一个“#”,
                                        而“#”属于特殊符号,特殊字符不会被当做参数,
                                        所以需要在前端做一下处理，转码转义一下。
                这里就是把前端传过来的已经转义的字符再转义回来；*/
        return "redirect:"+url;
        /*这里重定向到:https://open.weixin.qq.com/connect/oauth2/authorize
                    ?appid=APPID
                    &redirect_uri=REDIRECT_URI
                    &response_type=code
                    &scope=SCOPE
                    &state=STATE#wechat_redirect 的网址*/
    }
    @ApiOperation("获取微信用户信息，redirect_uri参数值指向的地址")
    @GetMapping("userInfo")
    public String userInfo(@RequestParam("code")String code,
                           @RequestParam("state")String returnUrl){
        try {//拿到code请求
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            //获取微信信息
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken,null);
            //添加微信个人信息到数据库
            UserInfo userInfo=new UserInfo();
            userInfo.setOpenId(wxMpOAuth2AccessToken.getOpenId());//openid
            userInfo.setNickName(wxMpUser.getNickname());//昵称
            userInfo.setAvatar(wxMpUser.getHeadImgUrl());//头像地址
            userInfo.setSex(wxMpUser.getSexId());//性别id
            userInfo.setProvince(wxMpUser.getProvince());//地址
            userInfoService.saveUserInfo(userInfo);
            String token= JWTHelper.createToken(userInfo.getId(),userInfo.getNickName());
            //这里首先将用户信息存在数据库中，然后将用户id和昵称放在token里面
            //便于之后生成订单之类的操作；
            if(returnUrl.indexOf("?")==-1){//通过检查里面有没有“?”来判断token是否是第一个参数;
                token="?token="+token;
            }else {
                token="&token="+token;
            }//这里的前端是通过判断是否有token来决定是否请求authorize
            //请求跳转方法跳转到userInfo方法来得到微信用户信息；
            return "redirect:"+returnUrl+token;
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new ClassroomException(20001,"微信用户登陆失败");
        }
    }
}
